package aos.client.gui;

import java.awt.AWTEvent;
import java.awt.Point;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import thinlet.Widget;
import thinlet.event.Listener;
import thinlet.layout.Metrics;


public class Pad extends Widget {

	float x = 0.5f;
	float y = 0.5f;
	private Listener changeListener;
	
	public void setValues(float x, float y) {
		x = Math.max(0, Math.min(x, 1));
		y = Math.max(0, Math.min(y, 1));
		
		if ((this.x != x) || (this.y != y)) {
			this.x = x;
			this.y = y;
			Listener.invoke(changeListener);
			repaint();
		}
	}
	
	public void addChangeListener(Listener listener) {
		changeListener = Listener.add(changeListener, listener);
	}
	
	public void removeChangeListener(Listener listener) {
		changeListener = Listener.remove(changeListener, listener);
	}
	
	protected boolean isFocusable() {
		return true;
	}
	
	public float getValueX() {
		return this.x;
	}
	
	public float getValueY() {
		return this.y;
	}
	
	protected void process(AWTEvent e) {
		switch (e.getID()) {
		case MouseEvent.MOUSE_ENTERED:
		case MouseEvent.MOUSE_EXITED:
			repaint();
			break;
		case MouseEvent.MOUSE_PRESSED:
			requestFocus();
		case MouseEvent.MOUSE_DRAGGED:
			setValues(((((MouseEvent) e).getX() - 7.0f) / (getWidth() - 7.0f)), ((((MouseEvent) e).getY() - 7.0f)  / (getHeight() - 7.0f)));
			repaint();
			break;
		case MouseEvent.MOUSE_RELEASED:
			repaint();
			break;
		case KeyEvent.KEY_PRESSED:
			KeyEvent ke = (KeyEvent) e;
			int code = ke.getKeyCode();
			
			if (code == KeyEvent.VK_LEFT) {
				setValues(this.x - 0.05f, this.y);
			}
			else if (code == KeyEvent.VK_UP) {
				setValues(this.x, this.y - 0.05f);
			}
			else if (code == KeyEvent.VK_RIGHT) {
				setValues(this.x + 0.05f, this.y);
			}
			else if (code == KeyEvent.VK_DOWN) {
				setValues(this.x, this.y + 0.05f);
			}
			break;
		case FocusEvent.FOCUS_GAINED:
		case FocusEvent.FOCUS_LOST:
			repaint();
		}
	}
	
	protected void paint(java.awt.Graphics2D g) {
		g.setColor(java.awt.Color.orange);
		g.fillOval((int)(this.x * (getWidth() - 14)), (int)(this.y * (getHeight() - 14)), 14, 14);
		g.setColor(java.awt.Color.LIGHT_GRAY);
		g.drawOval((int)(this.x * (getWidth() - 14)), (int)(this.y * (getHeight() - 14)), 14, 14);
	}
	
	
}
